const cloud = require('wx-server-sdk')
cloud.init({env: 'evn-cloud-a-4gf1q6iy9df62d73'})
const db = cloud.database()
const _ = db.command
const MAX_LIMIT = 100

const numberFormat = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}
/**
 * @param {date} 当前时日 
 */
const dateFormatter = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const dateStr = `${[year, month, day].map(numberFormat).join('-')}`
  return dateStr
}
/**
 * @description 检查总余额合法性,可用余额总额应大于待分配放生额总额 
 * @param waitAllotTotalAmount 待分配总金额
 * @returns isLegally: 合法true,非法false, sumBalance: 总余额，sumFreeAmount: 总放生额
*/
const checkTotalBalanceLegally = async (waitAllotTotalAmount) => {
  const date = await dateFormatter(new Date())
  const querySumBalanceResult = await db.collection('freeCaptiveDetails').aggregate().match({freeDate: date}).group({
    _id: '总余额',
    sumBalance: $.sum('$balance'),
    sumFreeAmount: $.sum('$freeAmount')
  }).end()
  const sumBalance = Number(querySumBalanceResult.list[0].sumBalance)
  const sumFreeAmount = Number(querySumBalanceResult.list[0].sumFreeAmount)
  const sum = sumBalance + sumFreeAmount
  if(sum >= waitAllotTotalAmount){
    return { isLegal: true,sumBalance: sumBalance, sumFreeAmount: sumFreeAmount }
  }
  return { isLegal: false, sumBalance: sumBalance, sumFreeAmount: sumFreeAmount }
}

/**
 * @description 获得平均额度
 * @param waitAllotTotalAmount: 待分配总金额
 * @returns 平均额度
 */
const getAvgAmount = async (waitAllotTotalAmount) => {
  const date = await dateFormatter(new Date())
  const queryResult = await db.collection('freeCaptiveDetails').where({
    freeDate: date,
    freeAmount: 0,
    balance: _.gt(0)
  }).count()
  console.log('查询结果为：', queryResult)
  const count = queryResult.total
  const avg = waitAllotTotalAmount / count
  return avg
}
module.exports = {
  checkTotalBalanceLegally,
  getAvgAmount
}